package controllers

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import play.api.db.slick._
import play.api.Play.current

import views._
import models._

object Resources extends Controller {

  val searchForm = Form("expression" -> text)

  // http://www.playframework.com/documentation/2.2.x/ScalaForms
  val resourceForm = Form(
    mapping(
      "id" -> optional(longNumber),
      "name" -> nonEmptyText,
      "version" -> optional(text),
      "uri" -> nonEmptyText,
      "group" -> longNumber
    )(Resource.apply)(Resource.unapply)
  )

  val Home = Redirect(routes.Resources.list)

  def index = Action { Home }

  def list = DBAction { implicit rs =>
    Ok(html.resource.list(GroupDAO.listWithResources()))
  }

 /**
   * Display the 'new resource form'.
   */
  def create = DBAction { implicit rs =>
     Ok(html.resource.admin(resourceForm, GroupDAO.options))
  }

  /**
   * Display the 'edit form' of an existing Resource
   *
   * @param id Id of the resource to edit
   */
  def edit(id: Long) = DBAction { implicit rs =>
    ResourceDAO.findById(id).map { resource =>
       Ok(html.resource.admin(resourceForm.fill(resource), GroupDAO.options))
     }.getOrElse(NotFound)
  }

  /**
   * Handle the form submission 
   *
   */
  def submit = DBAction { implicit rs =>
    resourceForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.resource.admin(formWithErrors, GroupDAO.options)),
      resource => {
        if (resource.id.isDefined) {
          ResourceDAO.update(resource)
        } else {
          ResourceDAO.insert(resource)
        }

        Home.flashing("success" -> "Resource %s has been saved".format(resource.name))
      }
    )
  }

  /**
   * Handle resource deletion
   */
  def delete(id: Long) = DBAction { implicit rs =>
    ResourceDAO.delete(id)
    Home.flashing("success" -> "Resource has been deleted")
  }

  def search = DBAction { implicit rs =>
    val expr = searchForm.bindFromRequest.get
    Logger.debug("Search expression is: %s".format(expr))
    Ok(html.resource.list(GroupDAO.listWithResources("%"+expr+"%")))
  }
}